const Book = require('../models/bookModel')

class BookController {
    static async create (ctx) {
        const {
            name,
            price,
            author,
            publicationDate,
            type,
            ISBN,
            quantity = 0,
            press,
        } = ctx.request.body ||
        {}
        const book = new Book({
            name, price, author, publicationDate, type, ISBN, quantity, press,
        })
        const res = await book.save()
        ctx.body = {
            code: 1,
            data: res,
            msg: '添加成功',
        }
    }

    static async update (ctx) {
        const { id, ...others } = ctx.request.body || {} // 扩展运算符 rest parameter
        const result = await Book.findOne({
            _id: id,
        }).exec()
        if (!result) {
            ctx.body = {
                code: 0,
                msg: '未找到书籍',
            }
            return
        }

        const newQuery = {}
        Object.entries(others).forEach(([key, value]) => {
            if (value === 0 || value) {
                newQuery[key] = value
            }
        })

        Object.assign(result, newQuery)
        const res = await result.save()
        ctx.body = {
            code: 1,
            data: res,
            msg: '更新成功',
        }
    }

    static async remove (ctx) {
        const { id } = ctx.params
        const res = await Book.deleteOne({
            _id: id,
        })
        ctx.body = {
            code: 1,
            data: res,
            msg: '删除成功',
        }
    }

    static async findList (ctx) {
        let { page = 1, size = 5, keyword = '' } = ctx.query
        size = Number(size)
        const total = await Book.countDocuments()
        const query = {}
        if (keyword) {
            query.name = new RegExp(keyword) //todo 通过正则，实现模糊查询
        }
        const list = await Book.find(query)
                               .sort({ _id: -1 })
                               .skip((page - 1) * size)
                               .limit(size)
                               .exec()
        ctx.body = {
            code: 1,
            data: {
                total,
                list,
                page,
                size,
            },
            msg: '获取成功',
        }
    }

    static async readDetails (ctx) {
        const { id } = ctx.params
        const result = await Book.findOne({
            _id: id,
        }).exec()

        if (!result) {
            ctx.body = {
                code: 0,
                msg: '没有找到书籍',
            }
            return
        }

        ctx.body = {
            code: 1,
            data: result,
            msg: '查询成功',
        }
    }
}

module.exports = BookController
